<?php

namespace App\Http\Requests\Order;

use App\Http\Requests\ApiRequest;
use App\Models\Order\Address;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\Guard;
use Illuminate\Validation\Validator;

/**
 * @property string country_id
 * @property string zone_id
 */
class OrderShippingRequest extends ApiRequest
{
    use ApiChecker;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'country_id' => 'required|int|min:1|max:'.self::MAX_INT,
            'zone_id'    => 'required|int|min:1|max:'.self::MAX_INT,
        ];
    }

    /**
     * @param Validator $validator
     * @throws \Exception
     */
    protected function afterValidator(Validator $validator)
    {
        $country_id = $this->country_id;
        $zone_id = $this->zone_id;
        $this->validateCustomerAddress($country_id, $zone_id);
    }

    /**
     * @param $country_id
     * @param $zone_id
     * @throws \Exception
     */
    private function validateCustomerAddress($country_id, $zone_id)
    {
        $address = (new Address)->where('country_id', $country_id)
            ->where('zone_id', $zone_id)
            ->where('customer_id', Guard::customer()->customer_id)
            ->first();

        $this->checkItemExist($address, trans('order.shipping_address_error'));
    }
}
